package cn.mlong.demo.git

import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeoutException

class OpenInGitBashAction : AnAction() {
    // 配置Git Bash路径（根据实际安装路径修改）
    private val gitBashPath = "D:\\Program Files\\Git\\git-bash.exe"
    private val LOG = Logger.getInstance(OpenInGitBashAction::class.java)
    private val settings = GitBashSettings.instance
    override fun getActionUpdateThread() = ActionUpdateThread.BGT

    override fun update(e: AnActionEvent) {
        // 只要选中了文件或文件夹都显示菜单项
        val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
        e.presentation.isEnabledAndVisible = file != null
    }

    override fun actionPerformed(e: AnActionEvent) {
        val project = e.project
        val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: run {
            showError(project, "请选择一个文件")
            return
        }

        try {
            // 获取文件所在目录路径
            val directoryPath = virtualFile.parent?.path ?: throw IOException("无法获取文件所在目录")

            // 验证Git Bash是否存在
            validateGitBashPath()

            // 启动Git Bash并切换到目标目录
            launchGitBash(directoryPath)

            showSuccess(project, directoryPath)
        } catch (ex: Exception) {
            handleError(project, ex)
        }
    }

    private fun validateGitBashPath() {
        val settings = GitBashSettings.instance
        val path = settings.gitBashPath

        if (path.isNullOrBlank()) {
            throw IOException("Git Bash路径未配置，请检查设置")
        }

        val gitBashFile = File(path)
        when {
            !gitBashFile.exists() ->
                throw IOException("Git Bash未找到，请确认路径是否正确: $path")
            !gitBashFile.canExecute() ->
                throw IOException("没有执行权限: $path")
        }
    }

    private fun launchGitBash(directoryPath: String) {
        try {
            // 启动Git Bash并切换到目标目录（不等待进程结束）
            ProcessBuilder(settings.gitBashPath, "--cd=\"$directoryPath\"")
                .directory(File(directoryPath))
                .start()
        } catch (e: IOException) {
            throw IOException("无法启动Git Bash: ${e.message}", e)
        }
    }


    private fun handleError(project: Project?, ex: Exception) {
        LOG.error("打开Git Bash失败", ex)

        val errorMessage = when (ex) {
            is IOException -> "无法启动Git Bash: ${ex.message}"
            is TimeoutException -> "Git Bash启动超时"
            else -> "发生错误: ${ex.message}"
        }

        showError(
            project, """
            $errorMessage
            
            可能原因:
            1. Git Bash未正确安装
            2. 路径配置不正确，请在Setting>Git Bash中选中你电脑的git-bash.exe（当前配置: $settings.gitBashPath);
            3. 目录访问权限不足
        """.trimIndent()
        )
    }

    private fun showSuccess(project: Project?, directoryPath: String) {
        LOG.info("已经打开git bash")
//        Messages.showInfoMessage(
//            project,
//            "已在Git Bash中打开目录: ${Paths.get(directoryPath).fileName}",
//            "打开成功"
//        )
    }

    private fun showError(project: Project?, message: String) {
        Messages.showErrorDialog(
            project,
            message,
            "打开失败"
        )
    }
}